package com.bw.module_mine.ui.login

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.util.TypedValue
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.navigation.NavController
import androidx.navigation.Navigation
import com.bw.lib_common.IntentData
import com.bw.lib_common.base.BaseFragment
import com.bw.lib_common.base.state.RequestEvent
import com.bw.lib_common.utils.ToastUtils
import com.bw.module_mine.R
import com.bw.module_mine.databinding.FragmentSmsCodeBinding
import com.bw.module_mine.ui.login.viewmodel.LoginViewModel
import kotlinx.coroutines.launch


class SmsCodeFragment : BaseFragment<LoginViewModel, FragmentSmsCodeBinding>() {
    private val mViewModel: LoginViewModel by activityViewModels()
    override val mLayoutResId: Int
        get() = R.layout.fragment_sms_code
    private lateinit var mNavController: NavController
    private lateinit var secSpan: ForegroundColorSpan
    private lateinit var textSpan: ForegroundColorSpan
    //获得跳转的参数：登录、重置、绑定
    private val mAction by lazy {
        arguments?.getString(IntentData.KEY_ACTION_SMS_CODE) ?: ""
    }
    private val mCountDownHandler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (System.currentTimeMillis() - mViewModel.sendSmsCodeTimeStamp > 60_000) {
                onCountDownFinished()
            } else {
                onTick(60 - (System.currentTimeMillis() - mViewModel.sendSmsCodeTimeStamp) / 1000)
            }
        }
    }
    //倒计时
    private fun onTick(sec: Long) {
        val content = "$sec 秒后重新获取"
        val builder = SpannableStringBuilder(content)
        builder.setSpan(secSpan, 0, content.indexOf("秒"), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        builder.setSpan(textSpan, content.indexOf("秒"), content.length, Spannable.SPAN_INCLUSIVE_INCLUSIVE)
        mBinding.tvCountDown.text = builder
        mCountDownHandler.sendEmptyMessageDelayed(1, 1_000)
    }
    override fun initView() {
        mNavController = Navigation.findNavController(mBinding.root)
        mViewModel.setShowingFragmentTag(SmsCodeFragment::class.java.simpleName)

        val typedValue = TypedValue()
        requireContext().theme.resolveAttribute(com.bw.lib_common.R.attr.colorTheme, typedValue, true)
        secSpan = ForegroundColorSpan(typedValue.data)
        requireContext().theme.resolveAttribute(com.bw.lib_common.R.attr.colorLightText, typedValue, true)
        textSpan = ForegroundColorSpan(typedValue.data)
    }

    override fun initData() {
        super.initData()
        mBinding.viewmodel = mViewModel
        //发送短信验证码
        mViewModel.getSmsCode(mAction)

    }

    override fun initListener() {
        super.initListener()
        //订阅发送短信的结果
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.requestSmsCode_.collect {
                    when (it) {
                        is RequestEvent.Success -> {
                            setLoadingViewVisible(false)
                            mBinding.verifyView.showSoftKeyBoard()
                            ToastUtils.showShort(requireActivity(),"验证码已经发送")
                            mViewModel.sendSmsCodeTimeStamp = System.currentTimeMillis() //记录发送时间戳
                            //开启倒计时
                            showCountDown()

                        }
                        is RequestEvent.Error -> {
                            setLoadingViewVisible(false)
                            ToastUtils.showShort(requireActivity(),it.msg)
                            //停止倒计时
                            onCountDownFinished()

                        }
                        is RequestEvent.Loading -> {
                            setLoadingViewVisible( true)
                        }
                        else -> {}
                    }
                }
            }
        }
        //订阅登录结果
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.requestLoginEvent_.collect{
                    when (it) {
                        is RequestEvent.Success -> {
                            setLoadingViewVisible(false)
                            //跳转到登录成功页面
                            (requireActivity() as LoginActivity).handleLoginSuccess()

                        }
                        is RequestEvent.Error -> {
                            setLoadingViewVisible(false)
                            ToastUtils.showShort(requireActivity(),it.msg)
                            mBinding.verifyView.hideSoftKeyBoard()
                        }
                        is RequestEvent.Loading -> {
                            setLoadingViewVisible( true)
                        }
                        else -> {}
                    }
                }

            }
        }
        //订阅重置密码结果
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED){
                mViewModel.requestResetEvent_.collect{
                    when (it) {
                        is RequestEvent.Success -> {
                            setLoadingViewVisible(false)
                            //跳转到登录成功页面
                            mNavController.navigate(R.id.action_smsCodeFragment_to_resetPwdFragment)

                        }
                        is RequestEvent.Error -> {
                            setLoadingViewVisible(false)
                            ToastUtils.showShort(requireActivity(),it.msg)
                            mBinding.verifyView.hideSoftKeyBoard()
                        }
                        is RequestEvent.Loading -> {
                            setLoadingViewVisible( true)
                        }
                        else -> {}
                    }
                }
            }
        }
        //验证码输入完成监听
        mBinding.verifyView.setOnInputVerifyCodeCompleted {
            if (mAction == SmsCode.LOGIN.type){
                mViewModel.loginBySmsCode(it)
            }else if (mAction == SmsCode.RESET.type){
                mViewModel.resetPwd(it)
            }else{

            }
        }
        //点击重新获得验证码
        mBinding.tvResend.setOnClickListener {
            //发送短信验证码
            mViewModel.getSmsCode(mAction)
        }
    }

    private fun onCountDownFinished() {
        mBinding.tvResend.visibility = View.VISIBLE
        mBinding.tvCountDown.visibility = View.GONE
    }

    private fun showCountDown() {
        mBinding.tvCountDown.visibility = View.VISIBLE
        mBinding.tvResend.visibility = View.GONE
        mCountDownHandler.sendEmptyMessage(1)
    }
}


enum class SmsCode(val type: String) {
    LOGIN("login"), RESET("rest"), BIND("bind")
}